<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */
    
    /*********************************************************
    *            --== InArch ==--
    *
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @copyright essentialmind.com 2005
    *
    *********************************************************/

    /***
    * class ajaxAddNode
    ****
    * This class will create a new node via an AJAX method
    ****
    * @package ajax
    * @author A Kulikov <a.kulikov@gmail.com>
    * @version n/a
    * @copyright essentialmind.com 2005
    ***/
    class ajaxPostComment extends ajaxAction{

        public function process(){

            /*
                id:     pid,
                type:   ptype,
                name:   document.getElementById('comment_name').value,
                mail:   document.getElementById('comment_email').value,
                url:    document.getElementById('comment_url').value,
                text:   document.getElementById('comment_comment').value,
                parent:
            */
            
            //see if we have all valid fields
            $_REQUEST['text'] = trim($_REQUEST['text']);
            $_REQUEST['name'] = trim($_REQUEST['name']);
            
            if(!$_REQUEST['text'] or !$_REQUEST['name']){
                $this->r->bad_inputs = true;
                return;
            }
            
            ## PreProcess Data ##
            #
            //prepare contents
            $_REQUEST['text'] = strip_tags($this->unescape($_REQUEST['text']),"<a>,<i>,<b>,<em>,<strong>,<blockqoute>,<q>");
            $_REQUEST['name'] = htmlspecialchars(trim($this->unescape($_REQUEST['name'])));
            $_REQUEST['mail'] = htmlspecialchars(trim($_REQUEST['mail']));

            //autolink
            $_REQUEST['text'] = preg_replace('#[^\"=]http://([^\s]*)#', ' [&nbsp;<b><a href="http://\\1">Link</a></b>&nbsp;]', $_REQUEST['text']);
            $_REQUEST['text'] = preg_replace('#^http://([^\s]*)#', ' [&nbsp;<b><a href="http://\\1">Link</a></b>&nbsp;]', $_REQUEST['text']);

            ###################################
            //parse contents through safehtml
            $_REQUEST['text'] = stripslashes($_REQUEST['text']);

            // Save all "<" symbols
            $_REQUEST['text'] = preg_replace("/<(?=[^a-zA-Z\/\!\?\%])/", "&lt;", $_REQUEST['text']);

            // Opera6 bug workaround
            $_REQUEST['text'] = str_replace("\xC0\xBC", "&lt;", $_REQUEST['text']);

            // Instantiate the handler  parser
            $parser           = new safeHTMLwrap();            
            $_REQUEST['text'] = $parser->parse($_REQUEST['text']);
            
            //fix some inputs
            $_REQUEST['text'] = ereg_replace("[\r\n|\r]","\n",trim($_REQUEST['text']));
            $_REQUEST['text'] = ereg_replace("[\r\n|\n|\r]{3,}","\n\n",$_REQUEST['text']);
            $_REQUEST['text'] = "<p>".nl2br($_REQUEST['text'])."</p>";
            
            ##
            if(!eregi('[-a-zA-Z0-9_\.]{1,}@[-a-zA-Z0-9_\.]{2,}\.[-a-zA-Z0-9_\.]{2,4}',$_REQUEST['mail'])){
                $_REQUEST['mail'] = null;
            }
            
            if($_REQUEST['url'] and !eregi('^http://',$_REQUEST['url'])){
                $_REQUEST['url'] = 'http://'.$_REQUEST['url'];
            }
            #
            ## /PreProcess
            
            //figure out group ID and user ID
            if($_SESSION['admin']){
                $gid = $_SESSION['admin']['gid'];
                $uid = $_SESSION['admin']['id'];
            }else{
                $gid = 1000;    // www group
                $uid = 1000;    // www user
                
                //set some nice cookies
                setcookie('cName',$_REQUEST['name'],time()+24*60*60*365,'/');
                setcookie('cMail',$_REQUEST['mail'],time()+24*60*60*365,'/');
                setcookie('cURL', $_REQUEST['url'], time()+24*60*60*365,'/');
            }

                        
            
            //now, I need to know where to shift it into
            $this->db->StartTrans();
            //$this->db->debug = 1;
            //is there a parent?
            if($_REQUEST['parent']){                
                $parent    = (int)$_REQUEST['parent'];
                $level     = $this->db->getOne("SELECT level + 1 FROM page_comments WHERE comment_id = ".$parent);
                $sortOrder = $this->getSortOrder($parent) + 1;
                
                //shift the whole list
                $this->db->query("UPDATE page_comments SET sortorder = sortorder + 1 WHERE pageid = ".(int)$_REQUEST['id']." AND pagetype = ".(int)$_REQUEST['type']." AND sortorder >= ".$sortOrder);
                
            }else{
                $sortOrder = (int)$this->db->getOne("SELECT max(sortorder) FROM page_comments WHERE pageid = ".(int)$_REQUEST['id']." AND pagetype = ".(int)$_REQUEST['type']) + 1;
                $level     = 1;
                $parent    = 'NULL';
            }
            
             $this->db->Execute("INSERT INTO 
                                        page_comments(pageid, pagetype, sender_name, sender_mail, sender_url, comment, owner_uid, owner_gid, sortorder, level, parent)
                                        VALUES(
                                            ".(int)$_REQUEST['id'].",
                                            ".(int)$_REQUEST['type'].",
                                            ".$this->db->qstr($_REQUEST['name']).",
                                            ".$this->db->qstr($_REQUEST['mail']).",
                                            ".$this->db->qstr($_REQUEST['url']).",
                                            ".$this->db->qstr($_REQUEST['text']).",
                                            ".$uid.",
                                            ".$gid.",
                                            ".$sortOrder.",
                                            ".$level.",
                                            ".$parent."
                                            )");
                                            
            //end transaction
            $this->db->CompleteTrans();
            
            //scroll to the new comment
            $this->r->commentID = $this->db->getOne("SELECT last_value FROM page_comments_comment_id_seq");
        }
            
        private function getSortOrder($commentID,$order=0){
            if($data = $this->db->getRow("SELECT comment_id, sortorder FROM page_comments WHERE parent = ".$commentID." ORDER BY sortorder DESC LIMIT 1")){
	        
                if($data['sortorder'] > $order){
                    $myOrder = $this->getSortOrder($data['comment_id'],$data['sortorder']);
                }else{
                    $myOrder = $order;
                }
            }else{
               $myOrder = (int)$this->db->getOne("SELECT sortorder FROM page_comments WHERE comment_id = '".$commentID."'");
            }
            
            return (int)$myOrder;
        }
    }
?>